package com.rinzin.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.rinzin.service.RestService;
import com.rinzin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @BelongsProject:microservice
 * @BelongsPackage:com.rinzin.controller
 * @Author:Rinzin
 * @CreateTime:2020-09-19-21-05
 * @Description:
 **/
@RestController
@RequestMapping("webapp")
public class UserController {

    @Autowired
    public EurekaClient eurekaClient;
    @Autowired
    LoadBalancerClient lb;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    UserService userService;

    @Autowired
    RestService restService;

    @Value("${server.port}")
    String port;

    @RequestMapping("getUser1")
    public String getUser1(){
        /**
         * 使用Feign进行服务的调用，创建一个接口，在接口写好调用的方法
         */
        String user = userService.getUser();
        return "consumer port:"+port+"==="+user;

        /**
         * 手动去获取Eureka中的服务，用RestTemplate进行服务调用
         */
        /*
        //根据服务id获取所有的服务实例
        List<InstanceInfo> instancesList = eurekaClient.getInstancesByVipAddress("UserService", false);
        String str1 = "";
        if(instancesList.size() > 0){
            InstanceInfo instanceInfo = instancesList.get(0);
            String url1 = "";
            if(instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP){
                url1 = "http://"+instanceInfo.getHostName() + ":" + instanceInfo.getPort() + "/user/info";
            }
            str1 = restTemplate.getForObject(url1, String.class);
        }

        ServiceInstance instance = lb.choose("UserService");
        String url2 = "http://"+instance.getHost() + ":" + instance.getPort() + "/user/info";

        String str2 = restTemplate.getForObject(url2, String.class);

        return "str1="+str1+",str2="+str2;*/
    }

    /**
     * 在使用RestTemplate,如何使用Hystrix进行熔断降级
     * @return
     */
    @RequestMapping("/getUser2")
    public String getUser2(){
        String user = restService.getUser();
        return user;
    }
}
